package cn.com.winning.ecare.activity;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.fasterxml.jackson.annotation.JsonUnwrapped;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.Constant;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.common.MyCircleDbp;
import cn.com.winning.ecare.common.MyCircleSbp;
import cn.com.winning.ecare.common.MyProgressDialog;
import cn.com.winning.ecare.common.MyTimeUtil;
import cn.com.winning.ecare.common.RoundProgressBar;
import cn.com.winning.ecare.model.YxtBprecords;
import cn.com.winning.ecare.utils.ClsUtils;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.JsonBuilder;
import cn.com.winning.ecare.utils.StringUtil;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.ArrayWheelAdapter;
import cn.com.winning.ecare.widgets.CustomProgressDialog;
import cn.com.winning.ecare.widgets.OnWheelChangedListener;
import cn.com.winning.ecare.widgets.WheelView;

/**
 * 健康测评-血压
 * 
 * @author Administrator
 */
@SuppressLint("NewApi")
public class BpBluetoothActivity extends Activity
{
	private BpBluetoothActivity oThis = this;
	private static final String LOG_TAG = BpBluetoothActivity.class.getName();
	private static final int SEARCHMSG = 0;
	private static final int RESULTMSG = 1;
	private static final int ERRORMSG = 2;
	private static final int SAVEBPMSG = 4;
	private static final int LASTRESULTMSG = 5;

	private Timer timer;
	private final int TIMEREXECUTE = 3;
	private final int CHECKTIME = 60 * 1000;
	MyApplication myApplication;

	private BluetoothAdapter blueadapter = null;
	private DeviceReceiver mydevice = new DeviceReceiver();
	private List<BluetoothDevice> deviceList = new ArrayList<BluetoothDevice>();
	private ListView deviceListview;
	private RelativeLayout bt_bottombar;
	private TextView btserch;
	private TextView bpbluetoothactivity_ssy;
	private TextView bpbluetoothactivity_szy;
	private TextView bpbluetoothactivity_clsj;
	private TextView bpbluetoothactivity_pulse;
	private TextView bpbluetoothactivity_describe;
	private boolean hasregister = false;
	private BluetoothDevice device = null;
	private BluetoothSocket socket = null;
	private String MYUUID = "00001101-0000-1000-8000-00805F9B34FB";
	private clientThread clientConnectThread = null;
	private ProcessReadThread mreadThread = null;
	private ImageButton menuButton;
	private ImageButton mainselected;
	private ImageButton bt_preview;
	private ImageButton bpbluetoothactivity_main_input;
	private ImageButton bpbluetoothactivity_ssy_img;
	private ImageButton bpbluetoothactivity_szy_img;
	private Button bpbluetoothactivity_cl;
	int screenheight;
	int screenwidth;
	AlertDialog alert_bluetooth = null;
	AlertDialog alert_input = null;
	MyAdapter adapter = null;
	MyCircleSbp arcProgressBarBig;
	MyCircleDbp arcProgressBarSmall;
	private int progressBig = 0;
	private int progressSmall = 0;
	Person person;
	CustomProgressDialog proDialog;// 加载框
	MyProgressDialog myProDialog;// 加载框
	RoundProgressBar myProgress;
	// private WheelView bpbluetoothactivity_main_input_wlsbp;
	// private WheelView bpbluetoothactivity_main_input_wldbp;
	// private WheelView bpbluetoothactivity_main_input_wlpulse;


	private ImageButton bpbluetoothactivity_main_input_back;
	private ImageButton bpbluetoothactivity_main_input_ok;
	private EditText bpbluetoothactivity_main_input_sbp;
	private EditText bpbluetoothactivity_main_input_dbp;
	private EditText bpbluetoothactivity_main_input_pulse;

	private YxtBprecords bprecords;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.bpbluetoothactivity);
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		// 获取屏幕分辨率
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenheight = dm.heightPixels;
		screenwidth = dm.widthPixels;
		// setContentView(R.layout.activity_main);
		// setView();
		// setBluetooth();
		findViews();
		setListeners();
		new Thread(new InitRecordThread()).start();
	}

	private void findViews()
	{
		menuButton = (ImageButton) findViewById(R.id.menuButton);
		mainselected = (ImageButton) findViewById(R.id.mainselected);
		bpbluetoothactivity_cl = (Button) findViewById(R.id.bpbluetoothactivity_cl);
		bpbluetoothactivity_clsj = (TextView) findViewById(R.id.bpbluetoothactivity_clsj);
		bpbluetoothactivity_clsj.setText("上次测量时间：" + MyTimeUtil.DateToStr(MyTimeUtil.yyyy_MM_dd_HH_mm_, new Date()));
		bpbluetoothactivity_ssy = (TextView) findViewById(R.id.bpbluetoothactivity_ssy);
		bpbluetoothactivity_szy = (TextView) findViewById(R.id.bpbluetoothactivity_szy);
		bpbluetoothactivity_pulse = (TextView) findViewById(R.id.bpbluetoothactivity_pulse);
		bpbluetoothactivity_describe = (TextView) findViewById(R.id.bpbluetoothactivity_describe);
		bpbluetoothactivity_ssy_img = (ImageButton) findViewById(R.id.bpbluetoothactivity_ssy_img);
		bpbluetoothactivity_szy_img = (ImageButton) findViewById(R.id.bpbluetoothactivity_szy_img);
		arcProgressBarBig = (MyCircleSbp) findViewById(R.id.arcProgressBarBig);
		arcProgressBarBig.setDiameter(200);
		arcProgressBarBig.setStrokewidth(30);
		arcProgressBarBig.init();
		arcProgressBarSmall = (MyCircleDbp) findViewById(R.id.arcProgressBarSmall);
		arcProgressBarSmall.setDiameter(140);
		arcProgressBarSmall.setStrokewidth(30);
		arcProgressBarSmall.init();
	}

	private void setListeners()
	{
		menuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				oThis.onBackPressed();
			}
		});
		mainselected.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View view)
			{

				Intent intent = new Intent();
				intent.setClass(oThis, BpHistory.class);
				startActivity(intent);
			}
		});
		bpbluetoothactivity_cl.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				if (alert_bluetooth != null && alert_bluetooth.isShowing())
				{
					alert_bluetooth.dismiss();
				}
				LayoutInflater flater = oThis.getLayoutInflater();
				final View view = flater.inflate(R.layout.bpbluetoothactivity_main, null);
				AlertDialog.Builder builder = new AlertDialog.Builder(oThis);
				alert_bluetooth = builder.create();
				alert_bluetooth.setView(view);
				alert_bluetooth.setCanceledOnTouchOutside(false);
				alert_bluetooth.show();
				WindowManager.LayoutParams params = alert_bluetooth.getWindow().getAttributes();
				params.width = screenwidth * 4 / 5;
				params.height = screenheight * 4 / 5;
				alert_bluetooth.getWindow().setAttributes(params);
				alert_bluetooth.getWindow().setContentView(R.layout.bpbluetoothactivity_main);
				deviceListview = (ListView) alert_bluetooth.findViewById(R.id.devicelist);
				adapter = new MyAdapter();
				deviceListview.setAdapter(adapter);
				deviceListview.setOnItemClickListener(new OnItemClickListener()
				{

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
					{
						final BluetoothDevice bluetoothDevice = deviceList.get(arg2);

						if (blueadapter != null && blueadapter.isDiscovering())
						{
							blueadapter.cancelDiscovery();
							btserch.setText("重新搜索");
						}

						AlertDialog.Builder dialog = new AlertDialog.Builder(oThis);// 定义一个弹出框对象
						dialog.setTitle("连接蓝牙设备");
						dialog.setMessage(bluetoothDevice.getName());
						dialog.setPositiveButton("连接", new DialogInterface.OnClickListener()
						{
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
								shutdownClient();
								device = bluetoothDevice;
								if ("BP:HC-503B".equals(device.getName()))
								{
									if (device.getBondState() == BluetoothDevice.BOND_NONE)
									{
										try
										{
											ClsUtils.setPin(device.getClass(), device, "1234");
											ClsUtils.createBond(device.getClass(), device);
										}
										catch (Exception e)
										{
											e.printStackTrace();
										}
									}
									else
									{
										clientConnectThread = new clientThread();
										clientConnectThread.start();
									}
								}

							}
						});
						dialog.setNegativeButton("取消", new DialogInterface.OnClickListener()
						{
							@Override
							public void onClick(DialogInterface dialog, int which)
							{
							}
						});
						dialog.show();

					}
				});
				bt_preview = (ImageButton) alert_bluetooth.findViewById(R.id.bt_preview);
				bt_preview.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{
						if (alert_bluetooth != null && alert_bluetooth.isShowing())
						{
							alert_bluetooth.dismiss();
						}
						shutdownClient();
					}
				});
				bpbluetoothactivity_main_input = (ImageButton) alert_bluetooth.findViewById(R.id.bpbluetoothactivity_main_input);
				bpbluetoothactivity_main_input.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{
						initInputDialog();
					}
				});
				btserch = (TextView) alert_bluetooth.findViewById(R.id.start_seach);
				bt_bottombar = (RelativeLayout) alert_bluetooth.findViewById(R.id.bt_bottombar);
				bt_bottombar.setOnClickListener(new ClinckMonitor());
				setBluetooth();
			}
		});
	}

	private void initInputDialog()
	{
		if (alert_input != null && alert_input.isShowing())
		{
			alert_input.dismiss();
		}
		LayoutInflater flater = oThis.getLayoutInflater();
		final View view = flater.inflate(R.layout.bpbluetoothactivity_main_input, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(oThis);
		alert_input = builder.create();
		alert_input.setView(view);
		alert_input.setCanceledOnTouchOutside(false);
		alert_input.show();
		WindowManager.LayoutParams params = alert_input.getWindow().getAttributes();
		params.width = screenwidth * 4 / 5;
		params.height = screenheight * 4 / 5;
		alert_input.getWindow().setAttributes(params);
		alert_input.getWindow().setContentView(R.layout.bpbluetoothactivity_main_input);
//		bpbluetoothactivity_main_input_wlsbp = (EditText) alert_input.findViewById(R.id.bpbluetoothactivity_main_input_wlsbp);
//		bpbluetoothactivity_main_input_wldbp = (EditText) alert_input.findViewById(R.id.bpbluetoothactivity_main_input_wldbp);
//		bpbluetoothactivity_main_input_wlpulse = (EditText) alert_input.findViewById(R.id.bpbluetoothactivity_main_input_wlpulse);
		bpbluetoothactivity_main_input_back = (ImageButton) alert_input.findViewById(R.id.bpbluetoothactivity_main_input_back);
		bpbluetoothactivity_main_input_back.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				if (alert_input != null && alert_input.isShowing())
				{
					alert_input.dismiss();
				}
			}
		});
		bpbluetoothactivity_main_input_ok = (ImageButton) alert_input.findViewById(R.id.bpbluetoothactivity_main_input_ok);
		bpbluetoothactivity_main_input_ok.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				if (StringUtil.isNotEmpty(bpbluetoothactivity_main_input_sbp.getText().toString())
						&& StringUtil.isNotEmpty(bpbluetoothactivity_main_input_dbp.getText().toString())
						&& StringUtil.isNotEmpty(bpbluetoothactivity_main_input_pulse.getText().toString()))
				{
					Message msg = myHandler.obtainMessage();
					Person p = new Person(Integer.parseInt(bpbluetoothactivity_main_input_sbp.getText().toString()), Integer
							.parseInt(bpbluetoothactivity_main_input_dbp.getText().toString()), Integer
							.parseInt(bpbluetoothactivity_main_input_pulse.getText().toString()), MyTimeUtil.DateToStr(
							MyTimeUtil.yyyy_MM_dd_HH_mm_, new Date()));
					msg.what = RESULTMSG;
					msg.obj = p;
					myHandler.sendMessage(msg);
					if (alert_input != null && alert_input.isShowing())
					{
						alert_input.dismiss();
					}
					if (alert_bluetooth != null && alert_bluetooth.isShowing())
					{
						alert_bluetooth.dismiss();
					}
				}
				else
				{
					Toast.makeText(oThis, "请输入您要填的数据，不要留空!", Toast.LENGTH_SHORT).show();
				}
			}
		});
		bpbluetoothactivity_main_input_sbp = (EditText) alert_input.findViewById(R.id.bpbluetoothactivity_main_input_sbp);
		bpbluetoothactivity_main_input_dbp = (EditText) alert_input.findViewById(R.id.bpbluetoothactivity_main_input_dbp);
		bpbluetoothactivity_main_input_pulse = (EditText) alert_input.findViewById(R.id.bpbluetoothactivity_main_input_pulse);
//		bpbluetoothactivity_main_input_sbp.setOnClickListener(new OnClickListener()
//		{
//
//			@Override
//			public void onClick(View v)
//			{
//
//				if (bpbluetoothactivity_main_input_wldbp != null && bpbluetoothactivity_main_input_wldbp.isShown())
//				{
//					bpbluetoothactivity_main_input_wldbp.setVisibility(View.INVISIBLE);
//				}
//				if (bpbluetoothactivity_main_input_wlpulse != null && bpbluetoothactivity_main_input_wlpulse.isShown())
//				{
//					bpbluetoothactivity_main_input_wlpulse.setVisibility(View.INVISIBLE);
//				}
//				bpbluetoothactivity_main_input_wlsbp.setVisibility(View.VISIBLE);
//				bpbluetoothactivity_main_input_wlsbp.setAdapter(new ArrayWheelAdapter<String>(Constant.SBP));// 滚轮适配器
//				if (StringUtil.isEmpty(bpbluetoothactivity_main_input_sbp.getText().toString()))
//				{
//					bpbluetoothactivity_main_input_wlsbp.setCurrentItem(80);
//				}
//				bpbluetoothactivity_main_input_wlsbp.addChangingListener(new OnWheelChangedListener()
//				{
//					public void onChanged(WheelView wheel, int oldValue, int newValue)
//					{
//						bpbluetoothactivity_main_input_sbp.setText(Constant.SBP[newValue].toString());
//						bpbluetoothactivity_main_input_sbp.setTextColor(Color.BLACK);
//					}
//				});
//			}
//		});

//		bpbluetoothactivity_main_input_dbp.setOnClickListener(new OnClickListener()
//		{
//
//			@Override
//			public void onClick(View v)
//			{
//
//				if (bpbluetoothactivity_main_input_wlsbp != null && bpbluetoothactivity_main_input_wlsbp.isShown())
//				{
//					bpbluetoothactivity_main_input_wlsbp.setVisibility(View.INVISIBLE);
//				}
//				if (bpbluetoothactivity_main_input_wlpulse != null && bpbluetoothactivity_main_input_wlpulse.isShown())
//				{
//					bpbluetoothactivity_main_input_wlpulse.setVisibility(View.INVISIBLE);
//				}
//				bpbluetoothactivity_main_input_wldbp.setVisibility(View.VISIBLE);
//				bpbluetoothactivity_main_input_wldbp.setAdapter(new ArrayWheelAdapter<String>(Constant.DBP));// 滚轮适配器
//				if (StringUtil.isEmpty(bpbluetoothactivity_main_input_dbp.getText().toString()))
//				{
//					bpbluetoothactivity_main_input_wldbp.setCurrentItem(50);
//				}
//				bpbluetoothactivity_main_input_wldbp.addChangingListener(new OnWheelChangedListener()
//				{
//					public void onChanged(WheelView wheel, int oldValue, int newValue)
//					{
//						bpbluetoothactivity_main_input_dbp.setText(Constant.DBP[newValue].toString());
//						bpbluetoothactivity_main_input_dbp.setTextColor(Color.BLACK);
//					}
//				});
//			}
//		});
//
//		bpbluetoothactivity_main_input_pulse.setOnClickListener(new OnClickListener()
//		{
//
//			@Override
//			public void onClick(View v)
//			{
//
//				if (bpbluetoothactivity_main_input_wldbp != null && bpbluetoothactivity_main_input_wldbp.isShown())
//				{
//					bpbluetoothactivity_main_input_wldbp.setVisibility(View.INVISIBLE);
//				}
//				if (bpbluetoothactivity_main_input_wlsbp != null && bpbluetoothactivity_main_input_wlsbp.isShown())
//				{
//					bpbluetoothactivity_main_input_wlsbp.setVisibility(View.INVISIBLE);
//				}
//				bpbluetoothactivity_main_input_wlpulse.setVisibility(View.VISIBLE);
//				bpbluetoothactivity_main_input_wlpulse.setAdapter(new ArrayWheelAdapter<String>(Constant.PULSE));// 滚轮适配器
//				if (StringUtil.isEmpty(bpbluetoothactivity_main_input_pulse.getText().toString()))
//				{
//					bpbluetoothactivity_main_input_wlpulse.setCurrentItem(50);
//				}
//				bpbluetoothactivity_main_input_wlpulse.addChangingListener(new OnWheelChangedListener()
//				{
//					public void onChanged(WheelView wheel, int oldValue, int newValue)
//					{
//						bpbluetoothactivity_main_input_pulse.setText(Constant.PULSE[newValue].toString());
//						bpbluetoothactivity_main_input_pulse.setTextColor(Color.BLACK);
//					}
//				});
//			}
//		});
	}

	@Override
	protected void onStart()
	{
		// 注册蓝牙接收广播
		if (!hasregister)
		{
			hasregister = true;
			IntentFilter filterStart = new IntentFilter(BluetoothDevice.ACTION_FOUND);
			IntentFilter filterEnd = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
			registerReceiver(mydevice, filterStart);
			registerReceiver(mydevice, filterEnd);
		}
		super.onStart();
	}

	@Override
	protected void onDestroy()
	{
		if (blueadapter != null && blueadapter.isDiscovering())
		{
			blueadapter.cancelDiscovery();
		}
		if (hasregister)
		{
			hasregister = false;
			unregisterReceiver(mydevice);
		}
		shutdownClient();
		super.onDestroy();
	}

	/**
	 * Setting Up Bluetooth
	 */
	private void setBluetooth()
	{
		blueadapter = BluetoothAdapter.getDefaultAdapter();

		if (blueadapter != null)
		{ // Device support Bluetooth
			// 确认开启蓝牙
			if (!blueadapter.isEnabled())
			{
				// 请求用户开启
				Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(intent, RESULT_FIRST_USER);
				// 使蓝牙设备可见，方便配对
				Intent in = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
				in.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200);
				startActivity(in);
				// 直接开启，不经过提示
				blueadapter.enable();
			}
		}
		else
		{ // Device does not support Bluetooth

			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setTitle("没有蓝牙设备");
			dialog.setMessage("不支持蓝牙，没有蓝牙设备");

			dialog.setNegativeButton("确定", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{

				}
			});
			dialog.show();
		}
	}

	/**
	 * Finding Devices
	 */
	private void findAvalibleDevice()
	{
		// 获取可配对蓝牙设备
		Set<BluetoothDevice> device = blueadapter.getBondedDevices();

		if (blueadapter != null && blueadapter.isDiscovering())
		{
			deviceList.clear();
			adapter.notifyDataSetChanged();
		}
		if (device.size() > 0)
		{ // 存在已经配对过的蓝牙设备
			for (Iterator<BluetoothDevice> it = device.iterator(); it.hasNext();)
			{
				BluetoothDevice btd = it.next();
				if (!deviceList.contains(btd))
				{
					deviceList.add(btd);
				}
				adapter.notifyDataSetChanged();
			}
		}
		else
		{ // 不存在已经配对过的蓝牙设备
			deviceList.clear();
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{

		switch (resultCode)
		{
			case RESULT_OK:
				findAvalibleDevice();
				break;
			case RESULT_CANCELED:
				break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private class ClinckMonitor implements OnClickListener
	{

		@Override
		public void onClick(View v)
		{
			if (blueadapter.isDiscovering())
			{
				blueadapter.cancelDiscovery();
				btserch.setText("重新搜索");
			}
			else
			{
				findAvalibleDevice();
				blueadapter.startDiscovery();
				btserch.setText("停止搜索");
			}
		}
	}

	/**
	 * 蓝牙搜索状态广播监听
	 * 
	 * @author Andy
	 */
	private class DeviceReceiver extends BroadcastReceiver
	{

		@Override
		public void onReceive(Context context, Intent intent)
		{
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action))
			{ // 搜索到新设备
				BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				// 搜索没有配过对的蓝牙设备
				if (btd.getBondState() != BluetoothDevice.BOND_BONDED)
				{
					if (!deviceList.contains(btd))
					{
						deviceList.add(btd);
					}
					adapter.notifyDataSetChanged();
				}
			}
			else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
			{ // 搜索结束

				if (deviceListview.getCount() == 0)
				{
					// deviceList.add("不存在已经配对过的蓝牙设备");
					adapter.notifyDataSetChanged();
				}
				btserch.setText("重新搜索");
			}
		}
	}

	// 蓝牙连接通讯

	private Handler myHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case SEARCHMSG:
					if (proDialog == null)
					{
						proDialog = CustomProgressDialog.createDialog(oThis);
					}
					proDialog.setMessage((String) msg.obj);
					proDialog.show();
					// proDialog.setCanceledOnTouchOutside(false);
					break;
				case ERRORMSG:
					if (myProDialog != null)
					{
						myProDialog.dismiss();
						myProgress.setVisibility(View.INVISIBLE);
					}
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					if (timer != null)
					{
						timer.cancel();// 关闭计时器
					}
					shutdownClient();
					break;
				case TIMEREXECUTE:
					if (myProDialog != null)
					{
						myProDialog.dismiss();
						myProgress.setVisibility(View.INVISIBLE);
					}
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Toast.makeText(oThis, "数据接收等待超时！", Toast.LENGTH_SHORT).show();
					if (timer != null)
					{
						timer.cancel();// 关闭计时器
					}
					shutdownClient();
					break;
				case RESULTMSG:
					if (myProDialog != null)
					{
						myProDialog.dismiss();
						myProgress.setVisibility(View.INVISIBLE);
					}
					if (alert_bluetooth != null && alert_bluetooth.isShowing())
					{
						alert_bluetooth.dismiss();
					}
					initPaintData(msg.obj);
					bprecords = new YxtBprecords();
					bprecords.setUsername(myApplication.getAccount());
					bprecords.setSbp(String.valueOf(person.sbp));
					bprecords.setDbp(String.valueOf(person.dbp));
					bprecords.setPulse(String.valueOf(person.pulse));
					bprecords.setClrq(MyTimeUtil.DateToStr(MyTimeUtil.yyyy_MM_dd, new Date()));
					bprecords.setClsj(person.clsj);
					new Thread(new SaveBpRecordThread()).start();
					break;
				case LASTRESULTMSG:
					if (myProDialog != null)
					{
						myProDialog.dismiss();
						myProgress.setVisibility(View.INVISIBLE);
					}
					if (alert_bluetooth != null && alert_bluetooth.isShowing())
					{
						alert_bluetooth.dismiss();
					}
					initPaintData(msg.obj);
					break;
				default:
					break;
			}
		}
	};

	private void initPaintData(Object obj)
	{
		person = new Person(0, 0, 0, MyTimeUtil.DateToStr(MyTimeUtil.yyyy_MM_dd_HH_mm_, new Date()));
		if (obj != null)
		{
			person = (Person) obj;
		}
		bpbluetoothactivity_ssy.setText(String.valueOf(person.sbp));
		if (person.sbp > 90 && person.sbp < 140)
		{
			bpbluetoothactivity_ssy.setTextColor(Color.parseColor("#9bc200"));
			bpbluetoothactivity_ssy_img.setVisibility(View.INVISIBLE);
		}
		else if (person.sbp >= 140)
		{
			bpbluetoothactivity_ssy.setTextColor(Color.parseColor("#ea5343"));
			bpbluetoothactivity_ssy_img.setVisibility(View.VISIBLE);
			bpbluetoothactivity_ssy_img.setBackgroundResource(R.drawable.high);
		}
		else
		{
			bpbluetoothactivity_ssy_img.setVisibility(View.VISIBLE);
			bpbluetoothactivity_ssy.setTextColor(Color.parseColor("#2d6d98"));
			bpbluetoothactivity_ssy_img.setBackgroundResource(R.drawable.low);
		}
		bpbluetoothactivity_szy.setText(String.valueOf(person.dbp));
		if (person.dbp > 60 && person.dbp < 90)
		{
			bpbluetoothactivity_szy.setTextColor(Color.parseColor("#9bc200"));
			bpbluetoothactivity_szy_img.setVisibility(View.INVISIBLE);
		}
		else if (person.dbp >= 90)
		{
			bpbluetoothactivity_szy_img.setVisibility(View.VISIBLE);
			bpbluetoothactivity_szy.setTextColor(Color.parseColor("#ea5343"));
			bpbluetoothactivity_szy_img.setBackgroundResource(R.drawable.high);
		}
		else
		{
			bpbluetoothactivity_szy_img.setVisibility(View.VISIBLE);
			bpbluetoothactivity_szy.setTextColor(Color.parseColor("#2d6d98"));
			bpbluetoothactivity_szy_img.setBackgroundResource(R.drawable.low);
		}
		bpbluetoothactivity_pulse.setText(String.valueOf(person.pulse) + "/分");
		bpbluetoothactivity_clsj.setText("上次测量时间：" + person.clsj);
		if ((person.sbp > 90 && person.sbp < 140) && (person.dbp > 60 && person.dbp < 90))
		{
			bpbluetoothactivity_describe.setText("正常血压");
			bpbluetoothactivity_describe.setTextColor(Color.parseColor("#9bc200"));
		}
		else if (person.sbp >= 140 || person.dbp >= 90)
		{
			bpbluetoothactivity_describe.setText("高血压");
			bpbluetoothactivity_describe.setTextColor(Color.parseColor("#ea5343"));
		}
		else if (person.sbp < 90 || person.dbp < 60)
		{
			bpbluetoothactivity_describe.setText("低血压");
			bpbluetoothactivity_describe.setTextColor(Color.parseColor("#2d6d98"));
		}
		initPaint();
		shutdownClient();
	}

	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case SAVEBPMSG:
					if (msg.obj != null)
					{
						Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					}
					break;
				default:
					break;
			}
		}
	};

	Handler mHandler = new Handler(new Callback()
	{
		@Override
		public boolean handleMessage(Message msg)
		{
			if (proDialog != null && proDialog.isShowing())
			{
				proDialog.dismiss();
			}
			if (myProDialog == null)
			{
				myProDialog = MyProgressDialog.createMyDialog(oThis, screenheight, screenwidth);
				myProDialog.show();
				// myProDialog.setCanceledOnTouchOutside(false);
				myProgress = myProDialog.getMyProgress();
			}
			if (myProDialog != null && !myProDialog.isShowing())
			{
				myProDialog.show();
				if (myProgress != null && myProgress.getVisibility() != 0)
				{
					myProgress.setVisibility(View.VISIBLE);
				}
			}
			myProgress.setMax(100);
			myProgress.setProgress(msg.what);
			return false;
		}
	});

	private void initPaint()
	{
		progressBig = 0;
		progressSmall = 0;
		new Thread(new Runnable()
		{
			public void run()
			{
				while (progressBig <= person.sbp)
				{
					if (person.sbp > 90 && person.sbp < 140)
					{
						arcProgressBarBig.setProcessColor(Color.parseColor("#9bc200"));
					}
					else if (person.sbp >= 140)
					{
						arcProgressBarBig.setProcessColor(Color.parseColor("#ea5343"));
					}
					else
					{
						arcProgressBarBig.setProcessColor(Color.parseColor("#2d6d98"));
					}
					arcProgressBarBig.postProgress(progressBig);
					progressBig++;
					try
					{
						Thread.sleep(15);
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				}
			}
		}).start();
		new Thread(new Runnable()
		{
			public void run()
			{
				while (progressSmall <= person.dbp)
				{
					if (person.dbp > 60 && person.dbp < 90)
					{
						arcProgressBarSmall.setProcessColor(Color.parseColor("#9bc200"));
					}
					else if (person.dbp >= 90)
					{
						arcProgressBarSmall.setProcessColor(Color.parseColor("#ea5343"));
					}
					else
					{
						arcProgressBarSmall.setProcessColor(Color.parseColor("#2d6d98"));
					}
					arcProgressBarSmall.postProgress(progressSmall);
					progressSmall++;
					try
					{
						Thread.sleep(15);
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	// 开启客户端
	private class clientThread extends Thread
	{
		@Override
		public void run()
		{
			try
			{
				Message msg = new Message();
				// 创建一个Socket连接：只需要服务器在注册时的UUID号
				if (device != null)
				{
					socket = device.createRfcommSocketToServiceRecord(UUID.fromString(MYUUID));
					// 连接
					msg.obj = "请稍候，正在连接设备:" + device.getName();
					msg.what = SEARCHMSG;
					myHandler.sendMessage(msg);
					socket.connect();
					msg = new Message();
					msg.obj = "设备连接成功，准备读取数据！";
					msg.what = SEARCHMSG;
					myHandler.sendMessage(msg);
					// 启动接受数据
					mreadThread = new ProcessReadThread(socket);
					mreadThread.start();
					timer = new Timer();
					timer.schedule(new TimerTask()
					{
						@Override
						public void run()
						{
							checkThread();
						}
					}, CHECKTIME);

				}
			}
			catch (IOException e)
			{
				Message msg = new Message();
				msg.obj = "连接设备异常！请重新试一试。";
				msg.what = ERRORMSG;
				myHandler.sendMessage(msg);
			}
		}
	};

	/* 停止客户端连接 */
	private void shutdownClient()
	{
		if (clientConnectThread != null)
		{
			clientConnectThread.interrupt();
			clientConnectThread = null;
		}
		if (mreadThread != null)
		{
			mreadThread.interrupt();
			mreadThread = null;
		}
		if (socket != null)
		{
			try
			{
				socket.close();
			}
			catch (IOException e)
			{

				e.printStackTrace();
			}
			socket = null;
		}
	}

	protected void checkThread()
	{
		Message msg = myHandler.obtainMessage();
		msg.what = TIMEREXECUTE;
		myHandler.sendMessage(msg);
	}

	class ProcessReadThread extends Thread
	{
		private BluetoothSocket socket;
		private DataInputStream dis;

		public ProcessReadThread(BluetoothSocket socket)
		{
			this.socket = socket;
			try
			{
				if (socket != null)
					dis = new DataInputStream(socket.getInputStream());
			}
			catch (IOException e)
			{
				e.printStackTrace();
				Message msg = myHandler.obtainMessage();
				msg.obj = "连接设备异常！请重新试一试。";
				msg.what = ERRORMSG;
				myHandler.sendMessage(msg);
			}
		}

		@Override
		public void run()
		{
			String str = "";
			int count = 0;
			Message msg = myHandler.obtainMessage();
			Message message = mHandler.obtainMessage();
			while (true)
			{
				try
				{
					final int data = dis.readUnsignedByte();
					char c = (char) Integer.parseInt(String.valueOf(data));
					str += c;
					count++;
					message = mHandler.obtainMessage();
					message.what = (100000 / 32) * count / 1000 + 1;
					mHandler.sendMessage(message);
					try
					{
						Thread.sleep(50);
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
					if (count >= 32 && str.indexOf("A000") != -1)
					{
						if (timer != null)
						{
							timer.cancel();// 关闭计时器
						}
						int sbp = Integer.parseInt(str.substring(4, 8), 16);
						int dbp = Integer.parseInt(str.substring(8, 10), 16);
						int pulse = Integer.parseInt(str.substring(10, 12), 16);
						Person p = new Person(sbp, dbp, pulse, MyTimeUtil.DateToStr(MyTimeUtil.yyyy_MM_dd_HH_mm_, new Date()));
						msg.what = RESULTMSG;
						msg.obj = p;
						myHandler.sendMessage(msg);
						if (dis != null)
						{
							dis.close();
						}
						if (socket != null)
						{
							socket.close();
						}
						break;
					}

				}
				catch (Exception e)
				{
					e.printStackTrace();
					msg.obj = "连接设备异常！请重新试一试。";
					msg.what = ERRORMSG;
					myHandler.sendMessage(msg);
					break;
				}
			}
		}
	}

	/**
	 * 自定义listview布局显示内容
	 * 
	 * @author zjj
	 */
	class MyAdapter extends BaseAdapter
	{

		public int getCount()
		{

			return deviceList.size();
		}

		public Object getItem(int position)
		{

			return deviceList.get(position);
		}

		public long getItemId(int position)
		{

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{

			ViewHolder holder = null;

			if (convertView == null)
			{

				holder = new ViewHolder();

				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.bpbluetoothactivity_item, null);

				holder.bpbluetoothactivity_item_img = (ImageView) convertView.findViewById(R.id.bpbluetoothactivity_item_img);
				holder.bpbluetoothactivity_item_title = (TextView) convertView.findViewById(R.id.bpbluetoothactivity_item_title);
				holder.bpbluetoothactivity_item_info = (TextView) convertView.findViewById(R.id.bpbluetoothactivity_item_info);
				convertView.setTag(holder);

			}

			else
			{

				holder = (ViewHolder) convertView.getTag();

			}
			holder.bpbluetoothactivity_item_img.setImageResource(R.drawable.small_44);
			if ("BP:HC-503B".equals(deviceList.get(position).getName()))
			{
				holder.bpbluetoothactivity_item_title.setText(deviceList.get(position).getName() + "(血压计)");
			}
			else
			{
				holder.bpbluetoothactivity_item_title.setText(deviceList.get(position).getName());
			}
			holder.bpbluetoothactivity_item_info.setText(deviceList.get(position).getAddress());
			return convertView;
		}

	}

	static class ViewHolder
	{

		ImageView bpbluetoothactivity_item_img;
		TextView bpbluetoothactivity_item_title;
		TextView bpbluetoothactivity_item_info;
	}

	private class Person
	{
		public final int sbp;
		public final int dbp;
		public final int pulse;
		public final String clsj;

		public Person(int sbp, int dbp, int pulse, String clsj)
		{
			super();
			this.sbp = sbp;
			this.dbp = dbp;
			this.pulse = pulse;
			this.clsj = clsj;
		}

	}

	private class SaveBpRecordThread implements Runnable
	{

		@Override
		public void run()
		{
			Looper.prepare();
			saveBpRecord();
			Looper.loop();
		}

	}

	private void saveBpRecord()
	{
		Message message = handler.obtainMessage();
		List<NameValuePair> ls = new ArrayList<NameValuePair>();
		String info = JsonBuilder.getInstance().toJson(bprecords);
		ls.add(new BasicNameValuePair("bprecords", info));
		JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.YXTBPRECORDSSAVEBPRECORD, ls);
		if (json != null)
		{
			// message.obj = "保存成功";
		}
		else
		{
			message.obj = "保存失败";
		}
		message.what = SAVEBPMSG;
		handler.sendMessage(message);
	}

	private class InitRecordThread implements Runnable
	{

		@Override
		public void run()
		{
			Looper.prepare();
			initBpRecord();
			Looper.loop();
		}

	}

	private void initBpRecord()
	{
		Message message = myHandler.obtainMessage();
		List<NameValuePair> ls = new ArrayList<NameValuePair>();
		ls.add(new BasicNameValuePair("username", myApplication.getAccount()));
		JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.YXTBPRECORDSFINDLASTRECORD, ls);
		try
		{
			if (json != null)
			{
				YxtBprecords bprecords = (YxtBprecords) JsonBuilder.getInstance().fromJson(json.getString("bpRecords"),
						YxtBprecords.class);
				int sbp = Integer.parseInt(StringUtil.isEmpty(bprecords.getSbp()) ? "0" : bprecords.getSbp());
				int dbp = Integer.parseInt(StringUtil.isEmpty(bprecords.getDbp()) ? "0" : bprecords.getDbp());
				int pulse = Integer.parseInt(StringUtil.isEmpty(bprecords.getPulse()) ? "0" : bprecords.getPulse());
				String clsj = StringUtil.isEmpty(bprecords.getClsj()) ? "0" : bprecords.getClsj();
				Person p = new Person(sbp, dbp, pulse, clsj);
				message.obj = p;
				message.what = LASTRESULTMSG;
			}
			else
			{
				message.obj = "数据获取失败";
				message.what = ERRORMSG;
			}
		}
		catch (Exception e)
		{
			message.obj = "数据获取失败";
			message.what = ERRORMSG;
		}

		myHandler.sendMessage(message);
	}

}
